package logic

import (
	"context"
	"io"
	"net/http"
	"strconv"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type AnswerLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAnswerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AnswerLogic {
	return &AnswerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AnswerLogic) Answer(req *types.AnswerReq) (resp *types.AnswerResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://api.nutpi.net/queryAnswerList?questionId=" + req.QId + "&page=" + req.Page
	res, err_ := httpc.Do(l.ctx, http.MethodGet, url, nil)
	if err_ != nil {
		l.Error(err_)
		return nil, err_
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}
	//格式化输出json
	// var str bytes.Buffer
	// _ = json.Indent(&str, []byte(body), "", "    ")
	// l.Debugf("formated: ", str.String())
	//l.Debug(keyValue)
	var responseData []types.AnswerItem
	var item types.AnswerItem
	recs := gjson.GetBytes(body, "records")
	recs.ForEach(func(key, value gjson.Result) bool {
		item.ID = value.Get("id").String()
		item.Account = value.Get("account").String()

		item.QuestionId = value.Get("questionId").String()
		item.Content = value.Get("content").String()
		item.IsMarkdown = value.Get("isMarkdown").Bool()
		item.MarkdownContent = value.Get("markdownContent").String()
		item.PostTime = value.Get("postTime").String()
		item.AvatarPath = value.Get("avatarPath").String()
		item.AvatarName = value.Get("avatarName").String()

		item.Nickname = value.Get("nickname").String()
		item.UserName = value.Get("username").String()
		item.TotalReply = value.Get("totalReply").String()
		// 解析 answerReplyList
		replylist := value.Get("answerReplyList")
		replylist.ForEach(func(_, tagValue gjson.Result) bool {
			var tag types.ReplyItem
			tag.ID = tagValue.Get("id").String()
			tag.Account = tagValue.Get("account").String()
			tag.QuestionId = tagValue.Get("questionId").String()
			tag.Content = tagValue.Get("content").String()
			tag.PostTime = tagValue.Get("postTime").String()
			tag.AvatarPath = tagValue.Get("avatarPath").String()
			tag.AvatarName = tagValue.Get("avatarName").String()
			tag.Nickname = tagValue.Get("nickname").String()
			tag.UserName = tagValue.Get("username").String()
			tag.AnswerId = tagValue.Get("answerId").String()
			item.AnswerList = append(item.AnswerList, tag)
			return true
		})

		responseData = append(responseData, item)
		return true // keep iterating
	})

	//t := reflect.TypeOf(keyVal["count"])
	//l.Debugf("Type: %v\n", t)
	start, err := strconv.ParseInt(req.Page, 10, 64)
	if err != nil {
		// 处理错误
		start = 0
	}
	total, err := strconv.ParseInt(gjson.GetBytes(body, "totalrecord").String(), 10, 64)
	if err != nil {
		// 处理错误
		total = 0
	}
	resp = &types.AnswerResp{
		Code:    0,
		Message: res.Status,
		Data:    responseData,
		Count:   len(responseData),
		Start:   int(start),
		Total:   int(total),
	}
	return resp, nil

}
